/*
 * Socket.cpp
 *
 *  Created on: 2010-6-22
 *      Author: guobc
 */

#include "Socket.h"

namespace HA {

void Socket::socketAdd() {
	m_maxsocket = m_socket + 1;
	FD_ZERO(&m_wfds);
	FD_ZERO(&m_rfds);
}

void Socket::socketConnect(const char* domain, int port) {
	struct hostent* site;
	struct sockaddr_in addr;

	site = gethostbyname(domain);
	if (site == NULL) {
		m_good = false;
	}

	m_socket = socket(AF_INET, SOCK_STREAM, 0);
	if (m_socket < 0) {
		m_good = false;
	}

	memset(&addr, 0, sizeof(struct sockaddr_in));
	memcpy(&addr.sin_addr, site->h_addr_list[0], site->h_length);
	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);

	connect(m_socket, (struct sockaddr*) &addr, sizeof(struct sockaddr)) < 0 ? m_good
			= false
			: m_good = true;
	socketAdd();
}

void Socket::socketSend(const char*fmt, ...) {
	char BUF[1024];
	va_list argptr;
	va_start(argptr, fmt);
	vsprintf(BUF, fmt, argptr);
	va_end(argptr);

	FD_CLR(m_socket, &m_rfds);
	FD_SET(m_socket, &m_wfds);

	struct timeval tvl;
	tvl.tv_sec = 1;
	tvl.tv_usec = 0;

	int ret = select(m_maxsocket, &m_rfds, &m_wfds, NULL, &tvl);
	if (ret <= 0) {
		socketClose();
		m_good = false;
	} else {
		if (FD_ISSET(m_socket, &m_wfds)) {
			send(m_socket, BUF, strlen(BUF), 0) == -1 ? m_good = false : m_good
					= true;
			//			m_good = true;
		} else {
			socketClose();
			m_good = false;
		}
	}

}

void Socket::socketRead(char* buffer, int len) {

	FD_CLR(m_socket, &m_wfds);
	FD_SET(m_socket, &m_rfds);

	struct timeval tvl;
	tvl.tv_sec = 1;
	tvl.tv_usec = 0;
	int ret = select(m_maxsocket, &m_rfds, &m_wfds, NULL, &tvl);
	if (ret <= 0) {
		socketClose();
		m_good = false;
	} else {
		if (FD_ISSET(m_socket, &m_rfds)) {
			recv(m_socket, buffer, len, 0) > 0 ? m_good = true : m_good = false;
			//			m_good = true;
		} else {
			socketClose();
			m_good = false;
		}
	}
}
}

